import pandas as pd
import numpy as np
import re
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
import statsmodels.api as sm

# =======================
# 1. 读取数据
# =======================
df = pd.read_excel("data.xlsx", sheet_name="男胎检测数据")

# 把“检测孕周”解析成数字（如 11w+6 -> 11.86 周）
def parse_gw(s):
    if pd.isna(s):
        return np.nan
    s = str(s)
    m = re.search(r"(\d+)\s*w\+?\s*(\d+)?", s, re.IGNORECASE)
    if m:
        w = float(m.group(1))
        d = float(m.group(2)) if m.group(2) else 0.0
        return w + d/7.0
    try:
        return float(s)
    except:
        return np.nan

df["gest_wk"] = df["检测孕周"].apply(parse_gw)
df["bmi"] = pd.to_numeric(df["孕妇BMI"], errors="coerce")
df["yconc"] = pd.to_numeric(df["Y染色体浓度"], errors="coerce")

# 定义因变量：是否通过（y=1 表示 Y浓度≥0.04）
df["pass"] = (df["yconc"] >= 0.04).astype(int)

# 清洗数据：去掉缺失值 & 限定孕周范围
data = df.dropna(subset=["gest_wk","bmi","pass"])
data = data[(data["gest_wk"] >= 8) & (data["gest_wk"] <= 30)].copy()

# =======================
# 2. 构造特征 (t, b, t^2, b^2, t*b)
# =======================
X = data[["gest_wk","bmi"]].values
y = data["pass"].values

poly = PolynomialFeatures(degree=1, include_bias=True)
X_poly = poly.fit_transform(X)

# 特征名字方便展示
feature_names = poly.get_feature_names_out(["t","b"])

# =======================
# 3. 拟合逻辑回归 (statsmodels 输出系数)
# =======================
model = sm.Logit(y, X_poly)
result = model.fit()

print("系数估计值：")
for name, coef in zip(feature_names, result.params):
    print(f"{name}: {coef:.4f}")

print("\n显著性检验：")
print(result.summary())


